// 源插件
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import { NumberDivide, DateDiff, FormatnumberZero, Mover, DateStamp } from '@/function.js';

// 视图插件
import {
  BackTop,
  Empty,
  Spin,
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Upload,
} from 'antd';
import StandardTablePro from '@/components/UpgradeStandardTable/StandardTablePro';

// 外部组件
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Loading from '@/components/Loading/Loading';

// css OR less预编译器
import styles from './All.less';

// 图片

/**
 *  Describe:数据连接
 *  Created by xjc on 2019/5/15
 */

@connect(({ jinrong, loading }) => ({
  jinrong,
  loading: loading.models.jinrongRule,
}))
@Form.create()
class Asset extends PureComponent {
  componentWillMount() {}

  /**
   *  Describe:当前状态
   *  Created by xjc on 2019/5/15
   */

  state = {
    listLoading: false, // 加载状态
    selectedRows: [], // 选择行
    formValues: {
      num: 10,
      page: 1,
    }, // 表格参数
    /* pageValues:{current: 1, pageSize: 10, total: 0}, */
    StocksDetailVisible: false, // modal开关
    OptionVisible: false, // modal开关
    record: {}, // 当前行内容
    searchText: '', // 搜索内容
    columns: [], // 表头处理结果
    currentDataSource: [], // 表剩余数据
  };

  /**
   *  Describe:本地搜索
   *  Created by xjc on 2019/6/4
   */

  getColumnSearchProps = dataIndex => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={node => {
            this.searchInput = node;
          }}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, confirm)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
        />
        <Button
          type="primary"
          onClick={() => this.handleSearch(selectedKeys, confirm)}
          icon="search"
          size="small"
          style={{ width: 80, marginRight: 8 }}
        >
          搜索
        </Button>
        <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 80 }}>
          重置
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <Icon type="search" style={{ color: filtered ? '#1880ff' : '#181816', fontWeight: '700' }} />
    ),
    onFilter: (value, record) => {
      if (record[dataIndex] === '合计:') {
        return true;
      }
      return record[dataIndex] === null
        ? ''
        : record[dataIndex]
            .toString()
            .toLowerCase()
            .includes(value.toLowerCase());
    },
    onFilterDropdownVisibleChange: visible => {
      if (visible) {
        setTimeout(() => this.searchInput.select());
      }
    },
    render: text => <span>{text}</span>,
  });

  handleSearch = (selectedKeys, confirm) => {
    confirm();
    this.setState({ searchText: selectedKeys[0] });
  };

  handleReset = clearFilters => {
    clearFilters();
    this.setState({ searchText: '' });
  };

  getColumns() {
    return [
      {
        title: '股票',
        align: 'center',
        width: 110,
        dataIndex: 'stock',
        sorter: (a, b) => {
          if (b.stock === '合计:') {
            return false;
          }
          const c = [a.stock, b.stock].sort();
          if (c[0] === a.stock) {
            return 1;
          }
          return -1;
        },
        ...this.getColumnSearchProps('stock'),
      },
      {
        title: '数量',
        dataIndex: 'stockNumber',
        align: 'center',
        width: 90,
        sorter: (a, b) => {
          if (b.stock === '合计:') {
            return false;
          }
          return a.stockNumber - b.stockNumber;
        },
        render: (value, row, index) => {
          return <span>{NumberDivide(value)}</span>;
        },
      },
      {
        title: '已SellCall',
        dataIndex: 'sellCallNum',
        align: 'center',
        width: 90,
        sorter: (a, b) => {
          if (b.stock === '合计:') {
            return false;
          }
          return a.sellCallNum - b.sellCallNum;
        },
        render: (value, row, index) => {
          return <span>{NumberDivide(value)}</span>;
        },
      },
      {
        title: '剩余数量',
        dataIndex: 'lastSCNum',
        align: 'center',
        width: 90,
        sorter: (a, b) => {
          if (b.stock === '合计:') {
            return false;
          }
          return a.lastSCNum - b.lastSCNum;
        },
        render: (value, row, index) => {
          return <span>{NumberDivide(value)}</span>;
        },
      },
      {
        title: '对冲市值',
        dataIndex: 'hedgeMarketValue',
        align: 'center',
        width: 90,
        sorter: (a, b) => {
          if (b.stock === '合计:') {
            return false;
          }
          return a.hedgeMarketValue - b.hedgeMarketValue;
        },
        render: (value, row, index) => {
          return <span>{NumberDivide(value)}</span>;
        },
      },
      {
        title: '市值',
        dataIndex: 'marketValue',
        align: 'center',
        width: 90,
        sorter: (a, b) => {
          if (b.stock === '合计:') {
            return false;
          }
          return a.marketValue - b.marketValue;
        },
        render: (value, row, index) => {
          return <span>{NumberDivide(value)}</span>;
        },
      },
      {
        title: '成本价',
        dataIndex: 'costMoney',
        align: 'center',
        width: 90,
        sorter: (a, b) => {
          if (b.stock === '合计:') {
            return false;
          }
          return a.costMoney - b.costMoney;
        },
        render: (value, row, index) => {
          return <span>{NumberDivide(value, 2)}</span>;
        },
      },
    ];
  }

  handleStandardTableChange = (pagination, filtersArg, sorter, extra) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    this.setState({
      currentDataSource: extra.currentDataSource,
    });
    /* 导入列表数据 */
    dispatch({
      type: 'jinrong/GetAssetManagement',
      payload: {
        currentDataSource: extra.currentDataSource,
      },
      callback: res => {},
    });
  };

  /**
   *  Describe:视图
   *  Created by xjc on 2019/5/15
   */

  render() {
    const {
      loading,
      jinrong: { assets },
    } = this.props;
    const { listLoading, selectedRows, record, StocksDetailVisible, OptionVisible } = this.state;
    let columns = [];
    let stocksAll = {};
    if (columns.length === 0 && assets.code === 1) {
      columns = this.getColumns();
      stocksAll = {
        title: `${assets.listAll.updateTime}市值情况`,
        titleTotal: false,
        data: [
          { name: '团队负责资产总市值', value: assets.listAll.sumMarketValue },
          { name: '实值sell call市值', value: assets.listAll.actualValue },
          { name: '虚值sell call市值', value: assets.listAll.imaginaryValue },
          { name: '未 sell call市值', value: assets.listAll.unScValue },
        ],
        total: [],
        code: 1,
        showHeader: false,
        columns: [
          {
            title: '',
            width: 100,
            dataIndex: 'name',
            type: 'string',
          },
          {
            title: '',
            width: 100,
            type: 'number',
            dataIndex: 'value',
            render: (value, row, index) => {
              return (
                <span>
                  {typeof value === 'number' || typeof value === 'string'
                    ? `$${NumberDivide(value.toString())}`
                    : null}
                </span>
              );
            },
          },
        ],
      };
    }
    return (
      <PageHeaderWrapper title="金融团队资产管理">
        <Card>
          {assets.code === 0 ? (
            <Loading />
          ) : (
            <div>
              <Row>
                <Col md={12} sm={24}>
                  <StandardTablePro dataSource={stocksAll} />
                </Col>
              </Row>
              <br />
              <br />
              <StandardTable
                selectedRows={selectedRows}
                loading={listLoading}
                data={assets}
                title={() => (
                  <div style={{ textAlign: 'center', fontSize: '0.95rem' }}>
                    <span style={{ marginRight: 10 }}>空头对冲市值明细</span>
                  </div>
                )}
                columns={columns}
                style={{ tableLayout: 'fixed' }}
                className={styles.TableLayout}
                // scroll={{x: 1400, y: 618}}
                bordered
                onChange={this.handleStandardTableChange}
                pagination={false}
                rowClassName={(record, index) =>
                  record.stock === '合计:' ? styles.statisticssTableBackground : styles.ffffff
                }
                // rowKey="id"
              />
            </div>
          )}
        </Card>
      </PageHeaderWrapper>
    );
  }

  componentDidMount() {
    const { dispatch } = this.props;

    /* 导入列表数据 */
    dispatch({
      type: 'jinrong/GetAssetManagement',
      payload: {
        currentDataSource: this.state.currentDataSource,
      },
      callback: res => {
        this.setState({
          currentDataSource: res.list.shortAssetList,
        });
      },
    });
  }

  componentWillUnmount() {}
}

export default Asset;
